import Taro from '@tarojs/taro'

export default async function login() {
  return new Promise(resolve => {
    Taro.login({
      success: (login_res) => {
        if (login_res.code) {
          Taro.getSetting({
            success: (res) => {
              if (!res.authSetting['scope.userInfo']) {
                Taro.authorize({
                  scope: 'scope.userInfo',
                  success: () => {
                    getUserInfo().then(userInfo => {
                      resolve({
                        userInfo,
                        code: login_res.code
                      })
                    })
                  }, fail: () => {
                    Taro.showModal({
                      title: '温馨提示',
                      content: '简单的信任，是你我俩故事的开始',
                      showCancel: false, // 不展示取消按钮
                      success: (res) => {
                        if (res.confirm) {
                          Taro.openSetting({
                            success: (res) => {
                              res.authSetting = {
                                "scope.userInfo": true,
                              }
                            }
                          })
                        } else if (res.cancel) {
                          Taro.showToast({
                            title: '授权失败！',
                            icon: 'close',
                            duration: 2000
                          })
                        }
                      }
                    })
                  }
                })
              } else {
                getUserInfo().then(userInfo => {
                  resolve({
                    userInfo,
                    code: login_res.code
                  })
                })
              }
            }
          })

        }
      }
    })
  })
}


function getUserInfo() {
  return new Promise(resolve => {
    Taro.getUserInfo({
      withCredentials: true,
      lang: 'zh_CN',
      success: (res_user) => {
        resolve(res_user.userInfo)
      },
      fail: () => {
        Taro.showToast({
          title: '获取用户信息失败！',
          icon: 'close',
          duration: 2000
        })
      },
      complete: (res) => {
      }
    })
  })
}

// nickName: "啊尼啊塞呦"
// gender: 1
// language: "zh_CN"
// city: "太原"
// province: "山西"
// country: "中国"
// avatarUrl:''
